import { _decorator, Component, Label, ProgressBar, Tween, tween, TweenEasing, UIOpacity, v3 } from 'cc';
import { DataProxy } from '../../../frame/A-LIB/lib.b.data';
import { AudioManager } from '../../../frame/component/audio-manager';
import { ClientAPI } from '../../api/client.api';
import GameDC from '../../manager/data.game.center';
import GameManager from '../../manager/game.manager';
const { ccclass, property } = _decorator;

@ccclass('Loading')
export class Loading extends Component {

	@property(ProgressBar)
	private bar: ProgressBar = null;

	private lbl_progress: Label;

	private __porgress__ = 0;
	public get progress(){
		return this.__porgress__;
	}
	public set progress(value: number){
		this.__porgress__ = value;
		this.updateProgress(value);
	}

	protected onLoad(): void {
		this.bar.progress = 0;
		this.node.parent.children.forEach(node=>{
			if(node.name==='Camera'){
				void 0;
			}else{
				node.active = node==this.node;
			}
		});
		this.lbl_progress = this.bar.node.getChildByName('lbl-progress').getComponent(Label);
	}

    start() {
		this.setProgress(0.1);
		this.adaptUI();
		this.UIInit();
    }

	private adaptUI(){
		mtec.cc.adaptBackgroundNode(this.node.getChildByName('background'));
	}

	private updateProgress(progress: number){
		this.bar.progress = progress;
		this.lbl_progress.string = mtec.number.fixedNum(progress * 100, 2).toFixed(2) + '%';
	}

	private target_progress: number = 0;
	private setProgress(progress: number){
		progress = mtec.number.limit(progress, 0, 1);

		if(progress < this.bar.progress){
			return void 0;
		}

		Tween.stopAllByTarget(this);

		let tw = tween<Loading>(this);

		if(this.bar.progress < this.target_progress){
			tw = tw.to(0.5, {progress: this.target_progress});
		}else{
			tw = tw.set({progress: this.target_progress});
		}

		this.target_progress = progress;
		tw.to(10, {progress}).start();
	}
	private progressEnd(){
		Tween.stopAllByTarget(this);
		tween<Loading>(this)
		.to(0.2, {progress: 1})
		.start();
	}

	private UIInit(){
		['Camera', 'audio', 'home-bg', 'game', 'home-ui', 'transition', 'pop-up', 'float', 'guide', 'loading']
		.forEach((name, index)=>this.node.parent.getChildByName(name).setSiblingIndex(index));

		this.setProgress(0.2);
		GameManager.inited.then(()=>{
			console.log('loading inited');
			this.node.parent.children.forEach(node=>node.name=='Camera' ? void 0 : node.active = true);
			ClientAPI.CloseLoading();
			this.setProgress(0.99);
			if(!mtec.local.read(GameManager.AppName + 'GameInitFinish')){
				GameManager.userPoint('GameInitFinish');
				mtec.local.save(GameManager.AppName + 'GameInitFinish', 'GameInitFinish');
			}
			this.otherPreprocess().then(()=>this.enterGame());
		});
	}

	private otherPreprocess(){
		let np_pltp = new mtec.NudityPromise<'end'>();
		let reg_pltp = DataProxy.follow(GameDC.Trigger, 'PreLoadTilesProgress', ()=>{
			let [t, f] = GameDC.Trigger.PreLoadTilesProgress.split(',').map(Number);
			if(t===f){
				DataProxy.cancel(reg_pltp);
				np_pltp.resolve('end');
			}
		}, false);
		GameDC.Trigger.PreLoadTiles = true;

		let np_lcp = new mtec.NudityPromise<'end'>();
		let reg_lcp = DataProxy.follow(GameDC.Trigger, 'LiveCommentsProgress', ()=>{
			let [f, t] = GameDC.Trigger.LiveCommentsProgress.split(',').map(Number);
			if(t===f){
				DataProxy.cancel(reg_lcp);
				np_lcp.resolve('end');
			}
		}, false);

		return Promise.all([np_pltp.promise, np_lcp.promise]);
	}


	private async enterGame(){
		if(!mtec.local.read(GameManager.AppName + 'GameStart')){
			GameManager.userPoint('GameStart');
			mtec.local.save(GameManager.AppName + 'GameStart', 'GameStart');
		}
		this.progressEnd();
		await mtec.delay(0.2, 'end');

		let [bg, logo, bar] = ['background', 'logo', 'progress'].map(name=>this.node.getChildByName(name));

		let [va_bar, va_logo] = [bar, logo].map(n=>new mtec.cc.VecAssist(n));
		va_bar.getPosition('center', 'over_bottom').x = bar.position.x;
		va_logo.getPosition('center', 'over_top').x = logo.position.x;

		let duration = 0.8;
		const easing: TweenEasing = 'cubicOut';
		tween(logo).to(duration, {position: va_logo.vec}, {easing}).start();
		tween(bar).to(duration, {position: va_bar.vec}, {easing}).start();

		let opt = bg.getComponent(UIOpacity);
		if(!opt) opt = bg.addComponent(UIOpacity);

		tween(opt).to(duration, {opacity: 0}, {easing}).start();
		tween(bg).to(duration, {scale: v3(1.5, 1.5, 1)}, {easing})
		.call(()=>{
			this.node.destroy();
			AudioManager.playBGM();
		}).start();

		GameDC.Trigger.LoadRound = GameDC.User.round;
		//GameDC.Trigger.LoadRound = 4;
		GameDC.Trigger.UIHome = true;
		GameDC.Trigger.UIGame = true;
		AudioManager.mute(!GameDC.User.bgm);
	}
}

